package com.draven.mall.controller;

import com.draven.mall.common.ApiResponse;
import com.draven.mall.entity.Admin;
import com.draven.mall.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理员控制器
 */
@RestController
@RequestMapping("/api/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public ApiResponse login(@RequestBody Map<String, String> loginForm) {
        String username = loginForm.get("username");
        String password = loginForm.get("password");
        
        // 验证用户名密码
        Admin admin = adminService.login(username, password);
        
        if (admin != null) {
            // 生成token
            String token = "admin-token-" + System.currentTimeMillis();
            
            Map<String, Object> data = new HashMap<>();
            data.put("id", admin.getId());
            data.put("username", admin.getUsername());
            data.put("name", admin.getName());
            data.put("token", token);
            
            return ApiResponse.success(data);
        } else {
            return ApiResponse.error("用户名或密码错误");
        }
    }
    
    /**
     * 获取管理员信息
     */
    @GetMapping("/info")
    public ApiResponse getInfo(@RequestParam String token) {
        // 在实际应用中，应该从token中解析用户信息
        // 这里简化处理，直接返回管理员信息
        Admin admin = adminService.getAdminByToken(token);
        
        if (admin != null) {
            Map<String, Object> data = new HashMap<>();
            data.put("id", admin.getId());
            data.put("username", admin.getUsername());
            data.put("name", admin.getName());
            data.put("role", "admin");
            
            return ApiResponse.success(data);
        } else {
            return ApiResponse.error("获取管理员信息失败");
        }
    }
    
    /**
     * 管理员退出登录
     */
    @PostMapping("/logout")
    public ApiResponse logout() {
        return ApiResponse.success("退出成功");
    }
    
    /**
     * 获取系统统计数据
     */
    @GetMapping("/dashboard")
    public ApiResponse getDashboard() {
        Map<String, Object> data = adminService.getDashboardData();
        return ApiResponse.success(data);
    }
} 